package repositories

import (
	"errors"
	"go_web/src/domain"
)
import "gorm.io/gorm"

type OrderRepository struct {
	db *gorm.DB
}

func NewOrderRepository(db *gorm.DB) OrderRepository {
	return OrderRepository{db: db}
}

// Create 创建订单
func (r OrderRepository) Create(order *domain.Order) error {
	return r.db.Create(order).Error
}

// UpdateByID 修改订单
func (r OrderRepository) UpdateByID(id uint, price float64, num int16) error {
	err := r.db.Exec("update order set price = ?,num=? where id = ?", price, num, id).Error
	return err

}

// DeleteByID 删除订单
func (r OrderRepository) DeleteByID(id uint) error {
	err := r.db.Exec("update order set delete = 1 where id = ?", id).Error
	return err

}

// FindByOrderNum 查询订单
func (r OrderRepository) FindByOrderNum(orderNum string) (*domain.Order, error) {
	var order domain.Order
	err := r.db.Raw("select * from order where order_num = ?", orderNum).Scan(&order).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &order, err
}

// FindByUserId 通过名称查询所有订单
func (r OrderRepository) FindByUserId(userId uint) (*[]domain.Order, error) {
	var order []domain.Order
	err := r.db.Raw("select * from order where user_id = ?", userId).Scan(&order).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, nil
	}
	return &order, err
}
